package controller

import (
	"ginEss/database"
	"ginEss/dto"
	"ginEss/middleware"
	"ginEss/model"
	"golang.org/x/crypto/bcrypt"
	"math/rand"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
)

func Register(ctx *gin.Context) {
	DB := database.GetDB()
	name := ctx.PostForm("name")
	telephone := ctx.PostForm("telephone")
	password := ctx.PostForm("password")
	// 手机号不为11位
	if len(telephone) != 11 {
		ctx.JSON(422, gin.H{
			"code": "422",
			"msg":  "手机号必须为11位",
		})
		return
	}
	// 密码小于11位
	if len(password) < 6 {
		ctx.JSON(422, gin.H{
			"code": "422",
			"msg":  "密码必须大于等于6位",
		})
		return
	}
	// 判断手机号是否存在
	if isTelephoneExist(DB, telephone) {
		ctx.JSON(422, gin.H{
			"code": "422",
			"msg":  "用户已经存在",
		})
		return
	}
	// 用户昵称为空
	if len(name) == 0 {
		name = DefalutName(11)
	}
	//密码加密
	hasedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		ctx.JSON(500, gin.H{
			"code": "500",
			"msg":  "密码加密错误",
		})
		return
	}
	newUser := model.User{
		Name:      name,
		Telephone: telephone,
		Password:  string(hasedPassword),
	}
	DB.Create(&newUser)
	ctx.JSON(200, gin.H{
		"code": "200",
		"msg":  "注册成功",
	})
}

func Login(ctx *gin.Context) {
	DB := database.GetDB()
	telephone := ctx.PostForm("telephone")
	password := ctx.PostForm("password")
	if len(telephone) != 11 {
		ctx.JSON(422, gin.H{
			"code": 422,
			"msg":  "电话必须为11位",
		})
		return
	}
	//判断手机号是否存在
	var user model.User
	DB.Table("users").Where("telephone = ?", telephone).First(&user)
	if user.ID == 0 {
		ctx.JSON(422, gin.H{
			"code": "422",
			"msg":  "用户不存在",
		})
		return
	}
	/***
	password之前转为string了,比较时重新转为字节切片
	*/
	err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
	if err != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"code": "422",
			"data": "密码错误",
			"msg":  "密码错误",
		})
		return
	}
	//密码正确,发放token
	token, err := middleware.ReleaseToken(user)
	if err != nil {
		ctx.JSON(500, gin.H{
			"code": "500",
			"msg":  "系统异常",
		})
		return
	}
	ctx.JSON(200, gin.H{
		"code":  200,
		"msg":   "登录成功",
		"token": token,
	})
}

func Info(ctx *gin.Context) {
	user, _ := ctx.Get("user")
	ctx.JSON(200, gin.H{
		"code": 200,
		"user": dto.ToUserDto(user.(model.User)),
	})
}

func isTelephoneExist(db *gorm.DB, telephone string) bool {
	var user model.User
	db.Where("telephone = ?", telephone).First(&user)
	return user.ID != 0
}

func DefalutName(n int) string {
	var letters = []byte("qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM")
	result := make([]byte, n)
	rand.Seed(time.Now().Unix())
	for i := range result {
		result[i] = letters[rand.Intn(len(letters))]
	}
	return string(result)
}
